var express = require("express");
var router = express.Router();
var request = require('request');
var qs = require('qs');


router.post('/login',function(req,res) {//登录
    var url = 'http://39.106.9.239/ATM/tokens/login';
    var formData = {
        "cardNo" : req.body.cardNo,
        "password" : req.body.password
    }
    var user = req.body.cardNo;
    var password = req.body.password;
    var reg = /^\d{19}$/g;
    var reg_2 = /^\d{6}$/g
    if(user == ""){
        res.end();
    }else if(!reg.test(user)) {
        res.end();
    }else if(password == "") {
        res.end();
    }else if(!reg_2.test(password)) {
        res.end();
    }else {
        request({
            url: url,
            method: "post",
            headers: {
                "content-type" : "application/x-www-form-urlencoded"
            },
            body: qs.stringify(formData)
        },function(_err,_res,_resBody){
            var body = JSON.parse(_resBody); 
            if(!_err && _res.statusCode == 200) {
                console.log(body.code);
                switch(body.code) {
                    case 0:
                    req.session.cardNo = body.data.cardNo;
                    req.session.token = body.data.token;
                    res.send(_resBody);
                    break;
                    case 100:
                    case 114: //冻结
                    case 123://密码错误
                    case 113://账号不存在
                    res.send(_resBody);
                    break;
                }
            }
        })
    }
});
router.get('/logout',function(req,res) {//登出
    if(req.session.token) {
        var url = 'http://39.106.9.239/ATM/tokens/logout';
    request({
        url: url,
        method: "post",
        headers: {
            "authorization" : req.session.token,
            "deviceNo" : 100
        }
    },function(_err,_res,_resBody){
        if(!_err && _res.statusCode == 200) {
            req.session.destroy();
            res.redirect("/");
        }else {
            console.log(_err);
        }
    });
    }else {
        res.redirect("/");
    }
});
module.exports = router;